package com.soyoung.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


/**
 * @author: zhq
 * @since : 2018/5/3
 */
@Component
public class RedisClient {

    @Autowired
    private JedisPool jedisPool;

    /**
     * 获取redis连接
     * @return
     */
    public Jedis getResource(){
        Jedis jedis = jedisPool.getResource();
        System.out.println("####get a jedis resource#####");
        return jedis;
    }

    /**
     * 获取redis连接
     * @return
     */
    public void returnResource(Jedis jedis){
        if (jedis!=null){
            jedis.close();
        }
        System.out.println("####return a jedis resource#####");
    }

    public int set(String key, String value,Integer times){
        int result=1;
        Jedis jedis =null;
        try {
            jedis = getResource();
            jedis.setex(key, times, value);
        }catch (Exception e){
            result = 0;
        }
        finally {
            //返还到连接池
            returnResource(jedis);
        }
        return result;
    }

    public Long setnx(String key, String value,Integer times){
        Long result=0L;
        Jedis jedis =null;
        try {
            jedis = getResource();
            result = jedis.setnx(key,value);
        }catch (Exception e){
            result = 0L;
        }
        finally {
            //返还到连接池
            returnResource(jedis);
        }
        return result;
    }

    public String get(String key)  {
        Jedis jedis = getResource();
        String values = "";
        try {
            values = jedis.get(key);
        }catch (Exception e){
            System.out.println("获取redis key error...");
        }finally {
            //返还到连接池
            returnResource(jedis);
        }
        return values;
    }
}
